package com.toman.ui.operation.enterprise.preheat;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Adpter.StateOpenExpandableListViewAdapter;
import com.toman.Entity.StateSelect_Entity;
import com.toman.Interfaces.BaseUrl;
import com.toman.MyApplication;
import com.toman.R;
import com.toman.Util.IntentUtils;
import com.toman.Util.ToastUtil;
import com.toman.toolbar.ToolBarActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import me.leefeng.promptlibrary.PromptDialog;
import okhttp3.Request;
import okhttp3.Response;

public class PreheatActivity extends ToolBarActivity {

    @BindView(R.id.ll_edit)
    LinearLayout llEdit;
    @BindView(R.id.btn_start)
    Button btnStart;
    @BindView(R.id.btn_stop)
    Button btnStop;
    private ArrayList<String> arrayList = new ArrayList<String>();
    PromptDialog promptDialog;

    /**
     * 所有分组的所有子项的 GridView 数据集合
     */
    private ArrayList<ArrayList<StateSelect_Entity>> array = new ArrayList<ArrayList<StateSelect_Entity>>();

    ExpandableListView mState_Expandable;
    BGARefreshLayout mState_refresh;

    @Override
    protected void onResume() {
        super.onResume();
        user();
    }

    JSONObject jsonObject;
    StateOpenExpandableListViewAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preheat);
        ButterKnife.bind(this);
        initToolBar("批量预热列表", getResources().getColor(R.color.c1));
        initHandler();
        initView();
    }

    private void initView() {
        promptDialog = new PromptDialog(this);

        mState_refresh = (BGARefreshLayout) findViewById(R.id.mState_refresh);
        mState_Expandable = (ExpandableListView) findViewById(R.id.mState_Expandable);
        // 隐藏分组指示器
        mState_Expandable.setGroupIndicator(null);
        adapter = new StateOpenExpandableListViewAdapter(this, arrayList, array, myApplication, mHandler);
        ;
        mState_Expandable.setAdapter(adapter);
        mState_refresh.setIsShowLoadingMoreView(true);
        mState_refresh.setRefreshViewHolder(new BGANormalRefreshViewHolder(MyApplication.getInstance(), true));

        mState_refresh.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
                if (true) {
                    // 如果网络可用，则加载网络数据

                    user();

                } else {
                    // 网络不可用，结束下拉刷新
                    mState_refresh.endRefreshing();
                }
            }

            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
                return false;
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_refresh, menu);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_refresh:
                        user();
                        break;
                }
                return false;
            }
        });

        return true;
    }

    public void user() {
        ToastUtil.print(token);
        OkHttpUtils
                .post(BaseUrl.preheat_list)
                .params("token", token)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "预热状态列表: " + result);
                        arrayList.clear();
                        array.clear();
                        arrayList.add("可预热");
                        arrayList.add("不可预热");

                        try {
                            JSONObject js = new JSONObject(result);
                            jsonObject = js;
                            int code = js.getInt("code");
                            if (code == 1) {
                                JSONObject data = js.getJSONObject("data");


                                JSONArray le = data.getJSONArray("preheat_list");
                                ArrayList<StateSelect_Entity> arrayList1 = new ArrayList<StateSelect_Entity>();
                                ArrayList<StateSelect_Entity> arrayList2 = new ArrayList<StateSelect_Entity>();
                                for (int k = 0; k < le.length(); k++) {
                                    JSONObject jas = le.getJSONObject(k);
                                    int beltline_id = jas.getInt("id");
                                    String beltline_name = jas.getString("beltline_name");
                                    String beltline_status = jas.getString("beltline_status");
                                    if (jas.getString("preheat").equals("ON")) {
                                        StateSelect_Entity en1;

                                        en1 = new StateSelect_Entity(beltline_id, beltline_name, "on", true);
                                        arrayList1.add(en1);

                                    } else {
                                        if (beltline_status.equals("Off")) {

                                            StateSelect_Entity en1;

                                            en1 = new StateSelect_Entity(beltline_id, beltline_name, beltline_status, true);


                                        arrayList1.add(en1);


                                    } else {

                                        StateSelect_Entity en2 = new StateSelect_Entity(beltline_id, beltline_name, beltline_status, false);
                                        arrayList2.add(en2);

                                        }
                                    }
                                }
                                array.add(arrayList1);
                                array.add(arrayList2);

                            }

                            for (int i = 0; i < array.size(); i++) {
                                mState_Expandable.expandGroup(i, true);


                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        adapter.notifyDataSetChanged();
                        mState_refresh.endRefreshing();

                    }
                });
    }

    //    public void startDialog() {
//        final AlertDialog dialog = new AlertDialog.Builder(this).create();
//        dialog.show();
//        dialog.getWindow().setContentView(R.item_data.del_layout3);
//        TextView textView = (TextView) dialog.getWindow().findViewById(R.id.tv_msg);
//        textView.setText("你确定要进行批量预热吗");
//        dialog.getWindow().findViewById(R.id.mDelUserDIomss).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                dialog.dismiss();
//            }
//        });
//        dialog.getWindow().findViewById(R.id.mDelUser).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (adapter.getSelectResult().equals("")) {
//                    Toast.makeText(getApplicationContext(), "暂无可预热设备，请添加后再试", Toast.LENGTH_SHORT).show();
//
//                    return;
//                }
//                OkHttpUtils
//                        .post(BaseUrl.batchStart)
//                        .params("token", token)
//                        .params("beltline_ids", adapter.getSelectResult())
//                        .execute(new StringCallback() {
//                            @Override
//                            public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
//                                try {
//                                    JSONObject js = new JSONObject(result);
//                                    int code = js.getInt("code");
//                                    if (code == 1) {
//                                        Toast.makeText(getApplicationContext(), "" + js.getString("msg"), Toast.LENGTH_SHORT).show();
//                                        user();
//                                        //customerManager();
//                                        dialog.dismiss();
//                                    } else {
//                                        Toast.makeText(getApplicationContext(), "" + js.getString("msg"), Toast.LENGTH_SHORT).show();
//                                        dialog.dismiss();
//                                    }
//                                } catch (JSONException e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                        });
//            }
//        });
//
//    }
    public void test() {
        if (adapter.getSelectResult().equals("")) {
            Toast.makeText(getApplicationContext(), "暂无可预热设备，请添加后再试", Toast.LENGTH_SHORT).show();

            return;
        }
        OkHttpUtils
                .post(BaseUrl.batchConfirm)
                .params("token", token)
                .params("beltline_ids", adapter.getSelectResult())
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        try {
                            JSONObject js = new JSONObject(result);
                            int code = js.getInt("code");
                            if (code == 1) {

                                start();
                                Toast.makeText(getApplicationContext(), "" + js.getString("msg"), Toast.LENGTH_SHORT).show();
                                //customerManager();

                            } else {
                                Toast.makeText(getApplicationContext(), "" + js.getString("msg"), Toast.LENGTH_SHORT).show();


                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    public void start() {
        if (adapter.getSelectResult().equals("")) {
            Toast.makeText(getApplicationContext(), "暂无可预热设备，请添加后再试", Toast.LENGTH_SHORT).show();

            return;
        }
        promptDialog.showLoading("正在操作");
        OkHttpUtils
                .post(BaseUrl.batchStart)
                .params("token", token)
                .params("beltline_ids", adapter.getSelectResult())
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        try {
                            JSONObject js = new JSONObject(result);
                            int code = js.getInt("code");
                            if (code == 1) {


                                promptDialog.showSuccess(js.getString("msg"));
                                user();
                                //customerManager();

                            } else {
//                                Toast.makeText(getApplicationContext(), "" + js.getString("msg"), Toast.LENGTH_SHORT).show();
                                promptDialog.showError(js.getString("msg"));


                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    public void startDialog() {

        //LayoutInflater是用来找layout文件夹下的xml布局文件，并且实例化

        new AlertDialog.Builder(this)
                //对话框的标题
                .setTitle("提示")
                //设定显示的View
                //对话框中的“登陆”按钮的点击事件
                .setMessage("你确定要开启批量预热？")
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        start();
                    }

                })
                .setNegativeButton("再想想", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create().show();

    }

    public void stop() {
        if (adapter.getStopResult().equals("")) {
            Toast.makeText(getApplicationContext(), "暂无可结束预热设备", Toast.LENGTH_SHORT).show();

            return;
        }
        promptDialog.showLoading("正在操作");
        OkHttpUtils
                .post(BaseUrl.batchStop)
                .params("token", token)
                .params("beltline_ids", adapter.getStopResult())
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        try {
                            JSONObject js = new JSONObject(result);
                            int code = js.getInt("code");
                            if (code == 1) {

                                promptDialog.showSuccess(js.getString("msg"));

//                                Toast.makeText(getApplicationContext(), "" + js.getString("msg"), Toast.LENGTH_SHORT).show();
                                user();
                                //customerManager();

                            } else {
                                promptDialog.showError(js.getString("msg"));


                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    public void stopDialog() {

        //LayoutInflater是用来找layout文件夹下的xml布局文件，并且实例化

        new AlertDialog.Builder(this)
                //对话框的标题
                .setTitle("提示")
                //设定显示的View
                //对话框中的“登陆”按钮的点击事件
                .setMessage("你确定要批量结束预热？")
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        stop();
                    }

                })
                .setNegativeButton("再想想", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create().show();

    }

    @OnClick({R.id.ll_edit, R.id.btn_start, R.id.btn_stop})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_edit:
                IntentUtils.startActivity(this, MutiOpenActivity.class);
                break;
            case R.id.btn_start:
//                startDialog();
                startDialog();
                break;
            case R.id.btn_stop:
                stopDialog();
                break;
        }
    }

    private void initHandler() {
        mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {

                    case 1:
                        user();

                        break;
                    default:
                        break;
                }
            }
        };
    }


}
